package com.isoftstone.util;


import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpConnectionUtil {

    /**
     * 根据配置文件决定做https 还是http
     * @param url
     * @return
     * @throws IOException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static HttpsURLConnection getHttpsConnection(URL url) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
        
               TrustManager[] tm = { new MyX509TrustManager1() };
               SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
               sslcontext.init(null, tm, new java.security.SecureRandom());
               // 从上述SSLContext对象中得到SSLSocktFactory对象
               SSLSocketFactory ssf = sslcontext.getSocketFactory();
               HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                       .openConnection();
               httpUrlConn.setSSLSocketFactory(ssf);
               httpUrlConn.setDoOutput(true);
               httpUrlConn.setDoInput(true);
               httpUrlConn.setUseCaches(false);

               return (HttpsURLConnection) url.openConnection();
           
        }

    public static HttpURLConnection getHttpConnection(URL url) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException {
            return (HttpURLConnection) url.openConnection();
        }

    }


class MyX509TrustManager1 implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}


